package org.example.springblogdemo.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class Md5Utils {
    //加密
    public static String enrypt(String password){
        String salt= UUID.randomUUID().toString().replace("-", "");
        //MD5(盐值+明文)
        String secretPassword=DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt+secretPassword;
    }
    //验证
    //true：密码正确，false：密码错误
    public static Boolean verify(String inputpassword, String sqlPassword){
        if (!StringUtils.hasLength(inputpassword)||!StringUtils.hasLength(sqlPassword)){
            return false;
        }
        if (sqlPassword.length()!=64){
            return false;
        }
        String salt=sqlPassword.substring(0, 32);
        String secretPassword=DigestUtils.md5DigestAsHex((salt+inputpassword).getBytes(StandardCharsets.UTF_8));
        return sqlPassword.equals(salt+secretPassword);
    }
}
